const { contextBridge, ipcRenderer } = require('electron')
const fs = require('fs')
const path = require('path')
const os = require('os')

let isDarkMode

contextBridge.exposeInMainWorld('preloadApi', {
  save: (url, content = '') => {
    // 默认保存到桌面
    const desktopDir = path.join(os.homedir(), 'Desktop')
    url = url || desktopDir
    console.log(url)
    console.log(content)
    if (!fs.existsSync(url)) {
      return alert(url + '路径不存在')
    }
    url = path.join(url, 'file.txt')
    fs.writeFile(url, content, 'utf-8', (err, data) => {
      if (err) return console.log(err)
      alert('保存成功')
    })
  },
  setTheme(theme) {
    ipcRenderer.send('setTheme', theme)
    ipcRenderer.invoke('isDarkMode').then((value) => {
      isDarkMode.innerHTML = value ? '是' : '否'
    })
  }
})

document.addEventListener('DOMContentLoaded', () => {
  isDarkMode = document.querySelector('#isDarkMode')
  ipcRenderer.invoke('isDarkMode').then((value) => {
    isDarkMode.innerHTML = value ? '是' : '否'
  })
})